package com.michale.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.michale.common.constants.UserConstant;
import com.michale.common.domain.system.DictDataEntity;
import com.michale.common.domain.system.DictTypeEntity;
import com.michale.common.exception.ServiceException;
import com.michale.common.utils.String.StringUtils;
import com.michale.common.utils.dict.DictUtils;
import com.michale.system.mapper.system.DictDataMapper;
import com.michale.system.mapper.system.DictTypeMapper;
import com.michale.system.service.DictTypeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Michale
 * @apiNote  字典类型管理 业务层
 */
@Service("dictTypeService")
public class DictTypeServiceImpl extends ServiceImpl<DictTypeMapper, DictTypeEntity> implements DictTypeService {

    @Resource
    private DictDataMapper sysDictDataMapper;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init() {
        loadingDictCache();
    }

    /**
     * 根据条件分页查询字典类型
     *
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public List<DictTypeEntity> selectDictTypeList(DictTypeEntity dictType) {
        return baseMapper.selectDictTypeList(dictType);
    }

    /**
     * 根据所有字典类型
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<DictTypeEntity> selectDictTypeAll() {
        return baseMapper.selectDictTypeAll();
    }

    /**
     * 根据字典类型ID查询信息
     *
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    public DictTypeEntity selectDictTypeById(Long dictId) {
        return baseMapper.selectDictTypeById(dictId);
    }

    /**
     * 根据字典类型查询信息
     *
     * @param dictType 字典类型
     * @return 字典类型
     */
    @Override
    public DictTypeEntity selectDictTypeByType(String dictType) {
        return baseMapper.selectDictTypeByType(dictType);
    }

    /**
     * 批量删除字典类型信息
     *
     * @param dictIds 需要删除的字典ID
     */
    @Override
    public void deleteDictTypeByIds(Long[] dictIds) {
        for (Long dictId : dictIds) {
            DictTypeEntity dictType = selectDictTypeById(dictId);
            if (sysDictDataMapper.countDictDataByType(dictType.getDictType()) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
            baseMapper.deleteDictTypeById(dictId);
            DictUtils.removeDictCache(dictType.getDictType());
        }
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache() {
        DictDataEntity dictData = new DictDataEntity();
        dictData.setStatus("0");
        Map<String, List<DictDataEntity>> dictDataMap = sysDictDataMapper.selectDictDataList(dictData).stream().collect(Collectors.groupingBy(DictDataEntity::getDictType));
        for (Map.Entry<String, List<DictDataEntity>> entry : dictDataMap.entrySet()) {
            DictUtils.setDictCache(entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(DictDataEntity::getDictSort)).collect(Collectors.toList()));
        }
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache() {
        DictUtils.clearDictCache();
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache() {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    public int insertDictType(DictTypeEntity dict) {
        int row = baseMapper.insertDictType(dict);
        if (row > 0) {
            DictUtils.setDictCache(dict.getDictType(), null);
        }
        return row;
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDictType(DictTypeEntity dict) {
        DictTypeEntity oldDict = baseMapper.selectDictTypeById(dict.getDictId());
        sysDictDataMapper.updateDictDataType(oldDict.getDictType(), dict.getDictType());
        int row = baseMapper.updateDictType(dict);
        if (row > 0) {
            List<DictDataEntity> dictDataList = sysDictDataMapper.selectDictDataByType(dict.getDictType());
            DictUtils.setDictCache(dict.getDictType(), dictDataList);
        }
        return row;
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public String checkDictTypeUnique(DictTypeEntity dict) {
        long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
        DictTypeEntity dictType = baseMapper.checkDictTypeUnique(dict.getDictType());
        if (StringUtils.isNotNull(dictType) && dictType.getDictId() != dictId) {
            return UserConstant.NOT_UNIQUE;
        }
        return UserConstant.UNIQUE;
    }
}